<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Swift 5 字符串插值增强 | KnightSama‘s Blog</title>
    <meta name="description" content="Hello, my friend!">
    <link rel="icon" href="/favicon.ico">
  <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
  <script src="https://cdn.jsdelivr.net/npm/react/umd/react.production.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/react-dom/umd/react-dom.production.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/@babel/standalone/babel.min.js"></script>
    
    <link rel="preload" href="/assets/css/0.styles.c4ea52a5.css" as="style"><link rel="preload" href="/assets/js/app.a2483de7.js" as="script"><link rel="preload" href="/assets/js/4.0078dadf.js" as="script"><link rel="preload" href="/assets/js/1.c3e7d2b0.js" as="script"><link rel="preload" href="/assets/js/26.70698c07.js" as="script"><link rel="prefetch" href="/assets/js/10.265e4f40.js"><link rel="prefetch" href="/assets/js/11.a3a2f8c1.js"><link rel="prefetch" href="/assets/js/12.1910f8cc.js"><link rel="prefetch" href="/assets/js/13.229fa478.js"><link rel="prefetch" href="/assets/js/14.c27d4a17.js"><link rel="prefetch" href="/assets/js/15.92adafd4.js"><link rel="prefetch" href="/assets/js/16.bcee7c14.js"><link rel="prefetch" href="/assets/js/17.ee1bcf41.js"><link rel="prefetch" href="/assets/js/18.fa3c3a4e.js"><link rel="prefetch" href="/assets/js/19.1a943c57.js"><link rel="prefetch" href="/assets/js/20.44781dae.js"><link rel="prefetch" href="/assets/js/21.1fe46223.js"><link rel="prefetch" href="/assets/js/22.6f7d46c2.js"><link rel="prefetch" href="/assets/js/23.56223d02.js"><link rel="prefetch" href="/assets/js/24.e7cad43b.js"><link rel="prefetch" href="/assets/js/25.b2902552.js"><link rel="prefetch" href="/assets/js/27.6ee3d263.js"><link rel="prefetch" href="/assets/js/28.ce131de6.js"><link rel="prefetch" href="/assets/js/29.90552487.js"><link rel="prefetch" href="/assets/js/30.b3291ccc.js"><link rel="prefetch" href="/assets/js/31.ea8c441e.js"><link rel="prefetch" href="/assets/js/32.3e29bbeb.js"><link rel="prefetch" href="/assets/js/33.65e78c5e.js"><link rel="prefetch" href="/assets/js/34.3ba19d7c.js"><link rel="prefetch" href="/assets/js/35.66d3fc4a.js"><link rel="prefetch" href="/assets/js/36.f5725281.js"><link rel="prefetch" href="/assets/js/37.f5b0b5ff.js"><link rel="prefetch" href="/assets/js/38.3cae3054.js"><link rel="prefetch" href="/assets/js/39.47dc1ffe.js"><link rel="prefetch" href="/assets/js/5.f0714e2e.js"><link rel="prefetch" href="/assets/js/6.53240a5f.js"><link rel="prefetch" href="/assets/js/7.dc126a6b.js"><link rel="prefetch" href="/assets/js/8.86452400.js"><link rel="prefetch" href="/assets/js/9.16ef06de.js"><link rel="prefetch" href="/assets/js/vendors~flowchart.734d5d92.js">
    <link rel="stylesheet" href="/assets/css/0.styles.c4ea52a5.css">
  </head>
  <body>
    <div id="app" data-server-rendered="true"><div><div class="theme-container" data-v-0cb1c278><div data-v-0cb1c278><div id="loader-wrapper" class="loading-wrapper" data-v-4b73742e data-v-0cb1c278 data-v-0cb1c278><div class="loader-main" data-v-4b73742e><div data-v-4b73742e></div><div data-v-4b73742e></div><div data-v-4b73742e></div><div data-v-4b73742e></div></div> <!----> <!----></div> <div class="password-shadow password-wrapper-out" style="display:none;" data-v-da0660ba data-v-0cb1c278 data-v-0cb1c278><h3 class="title" style="display:none;" data-v-da0660ba data-v-da0660ba>KnightSama‘s Blog</h3> <!----> <label id="box" class="inputBox" style="display:none;" data-v-da0660ba data-v-da0660ba><input type="password" value="" data-v-da0660ba> <span data-v-da0660ba>Konck! Knock!</span> <button data-v-da0660ba>OK</button></label> <div class="footer" style="display:none;" data-v-da0660ba data-v-da0660ba><span data-v-da0660ba><i class="iconfont reco-theme" data-v-da0660ba></i> <a target="blank" href="https://vuepress-theme-reco.recoluan.com" data-v-da0660ba>vuePress-theme-reco</a></span> <span data-v-da0660ba><i class="iconfont reco-copyright" data-v-da0660ba></i> <a data-v-da0660ba><span data-v-da0660ba>KnightSama</span>
            
          <!---->
          2021
        </a></span></div></div> <div class="hide" data-v-0cb1c278><header class="navbar" data-v-0cb1c278><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/" class="home-link router-link-active"><img src="/Misaka.jpg" alt="KnightSama‘s Blog" class="logo"> <span class="site-name">KnightSama‘s Blog</span></a> <div class="links"><div class="color-picker"><a class="color-button"><i class="iconfont reco-color"></i></a> <div class="color-picker-menu" style="display:none;"><div class="mode-options"><h4 class="title">Choose mode</h4> <ul class="color-mode-options"><li class="dark">dark</li><li class="auto active">auto</li><li class="light">light</li></ul></div></div></div> <div class="search-box"><i class="iconfont reco-search"></i> <input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><a href="/" class="nav-link"><i class="iconfont reco-home"></i>
  首页
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-category"></i>
      分类
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/categories/iOS/" class="nav-link"><i class="iconfont undefined"></i>
  iOS
</a></li><li class="dropdown-item"><!----> <a href="/categories/集锦/" class="nav-link"><i class="iconfont undefined"></i>
  集锦
</a></li><li class="dropdown-item"><!----> <a href="/categories/JavaScript/" class="nav-link"><i class="iconfont undefined"></i>
  JavaScript
</a></li><li class="dropdown-item"><!----> <a href="/categories/Github/" class="nav-link"><i class="iconfont undefined"></i>
  Github
</a></li><li class="dropdown-item"><!----> <a href="/categories/Python/" class="nav-link"><i class="iconfont undefined"></i>
  Python
</a></li></ul></div></div><div class="nav-item"><a href="/tag/" class="nav-link"><i class="iconfont reco-tag"></i>
  标签
</a></div><div class="nav-item"><a href="/timeline/" class="nav-link"><i class="iconfont reco-date"></i>
  时间线
</a></div><div class="nav-item"><a href="https://github.com/KnightSama" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="iconfont reco-github"></i>
  GitHub
  <svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a></div> <!----></nav></div></header> <div class="sidebar-mask" data-v-0cb1c278></div> <aside class="sidebar" data-v-0cb1c278><div class="personal-info-wrapper" data-v-4a3def3c><img src="/Misaka.jpg" alt="author-avatar" class="personal-img" data-v-4a3def3c> <h3 class="name" data-v-4a3def3c>
    KnightSama
  </h3> <div class="num" data-v-4a3def3c><div data-v-4a3def3c><h3 data-v-4a3def3c>27</h3> <h6 data-v-4a3def3c>文章</h6></div> <div data-v-4a3def3c><h3 data-v-4a3def3c>14</h3> <h6 data-v-4a3def3c>标签</h6></div></div> <hr data-v-4a3def3c></div> <nav class="nav-links"><div class="nav-item"><a href="/" class="nav-link"><i class="iconfont reco-home"></i>
  首页
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-category"></i>
      分类
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/categories/iOS/" class="nav-link"><i class="iconfont undefined"></i>
  iOS
</a></li><li class="dropdown-item"><!----> <a href="/categories/集锦/" class="nav-link"><i class="iconfont undefined"></i>
  集锦
</a></li><li class="dropdown-item"><!----> <a href="/categories/JavaScript/" class="nav-link"><i class="iconfont undefined"></i>
  JavaScript
</a></li><li class="dropdown-item"><!----> <a href="/categories/Github/" class="nav-link"><i class="iconfont undefined"></i>
  Github
</a></li><li class="dropdown-item"><!----> <a href="/categories/Python/" class="nav-link"><i class="iconfont undefined"></i>
  Python
</a></li></ul></div></div><div class="nav-item"><a href="/tag/" class="nav-link"><i class="iconfont reco-tag"></i>
  标签
</a></div><div class="nav-item"><a href="/timeline/" class="nav-link"><i class="iconfont reco-date"></i>
  时间线
</a></div><div class="nav-item"><a href="https://github.com/KnightSama" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="iconfont reco-github"></i>
  GitHub
  <svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a></div> <!----></nav>  <ul class="sidebar-links"><li><section class="sidebar-group depth-0"><p class="sidebar-heading open"><span>Swift 5 字符串插值增强</span> <!----></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/Views/20200318.html#扩展-string-的插值功能" class="sidebar-link">扩展 String 的插值功能</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header"><a href="/Views/20200318.html#原始输出" class="sidebar-link">原始输出</a></li><li class="sidebar-sub-header"><a href="/Views/20200318.html#格式化增强" class="sidebar-link">格式化增强</a></li></ul></li><li><a href="/Views/20200318.html#扩展自定义类型" class="sidebar-link">扩展自定义类型</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header"><a href="/Views/20200318.html#创建自定义类型" class="sidebar-link">创建自定义类型</a></li><li class="sidebar-sub-header"><a href="/Views/20200318.html#遵循-expressiblebystringliteral-协议" class="sidebar-link">遵循 ExpressibleByStringLiteral 协议</a></li><li class="sidebar-sub-header"><a href="/Views/20200318.html#遵循-expressiblebystringinterpolation-协议" class="sidebar-link">遵循 ExpressibleByStringInterpolation 协议</a></li><li class="sidebar-sub-header"><a href="/Views/20200318.html#使用" class="sidebar-link">使用</a></li></ul></li></ul></section></li></ul> </aside> <div class="password-shadow password-wrapper-in" style="display:none;" data-v-da0660ba data-v-0cb1c278><h3 class="title" style="display:none;" data-v-da0660ba data-v-da0660ba>Swift 5 字符串插值增强</h3> <!----> <label id="box" class="inputBox" style="display:none;" data-v-da0660ba data-v-da0660ba><input type="password" value="" data-v-da0660ba> <span data-v-da0660ba>Konck! Knock!</span> <button data-v-da0660ba>OK</button></label> <div class="footer" style="display:none;" data-v-da0660ba data-v-da0660ba><span data-v-da0660ba><i class="iconfont reco-theme" data-v-da0660ba></i> <a target="blank" href="https://vuepress-theme-reco.recoluan.com" data-v-da0660ba>vuePress-theme-reco</a></span> <span data-v-da0660ba><i class="iconfont reco-copyright" data-v-da0660ba></i> <a data-v-da0660ba><span data-v-da0660ba>KnightSama</span>
            
          <!---->
          2021
        </a></span></div></div> <div data-v-0cb1c278><main class="page"><div class="sidebar-open-close"><svg xmlns="http://www.w3.org/2000/svg" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <!----> <div class="page-title" style="display:none;"><h1>Swift 5 字符串插值增强</h1> <hr> <div data-v-73367bb4><i class="iconfont reco-account" data-v-73367bb4><span data-v-73367bb4>KnightSama</span></i> <i class="iconfont reco-date" data-v-73367bb4><span data-v-73367bb4>2020-03-18</span></i> <i class="iconfont reco-eye" data-v-73367bb4><span id="/Views/20200318.html" data-flag-title="Your Article Title" class="leancloud-visitors" data-v-73367bb4><a class="leancloud-visitors-count" style="font-size:.9rem;font-weight:normal;color:#999;"></a></span></i> <i class="iconfont reco-tag tags" data-v-73367bb4><span class="tag-item" data-v-73367bb4>
      Swift
    </span></i></div></div> <div class="theme-reco-content content__default" style="display:none;"><h2 id="扩展-string-的插值功能"><a href="#扩展-string-的插值功能" class="header-anchor">#</a> 扩展 String 的插值功能</h2> <p>在 Swift 中我们一般通过  <code>\(Any)</code>  的方式在 String 中插值，而在 Swift 5 中我们可以通过扩展  <code>String.StringInterpolation</code>  并实现带有不同参数的  <code>appendInterpolation</code>  方法来增强这一功能，这里以格式化输出时间为例</p> <h3 id="原始输出"><a href="#原始输出" class="header-anchor">#</a> 原始输出</h3> <div class="tabs-component"><ul role="tablist" class="tabs-component-tabs"></ul> <div class="tabs-component-panels"><section aria-hidden="true" id="swift" role="tabpanel" class="tabs-component-panel" style="display:none;"><div class="language-swift line-numbers-mode"><pre class="language-swift"><code><span class="token function">print</span><span class="token punctuation">(</span><span class="token string">&quot;\(Date())&quot;</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div></section> <section aria-hidden="true" id="输出" role="tabpanel" class="tabs-component-panel" style="display:none;"><p>2020-03-18 07:15:51 +0000</p></section></div></div> <h3 id="格式化增强"><a href="#格式化增强" class="header-anchor">#</a> 格式化增强</h3> <div class="tabs-component"><ul role="tablist" class="tabs-component-tabs"></ul> <div class="tabs-component-panels"><section aria-hidden="true" id="swift" role="tabpanel" class="tabs-component-panel" style="display:none;"><div class="language-swift line-numbers-mode"><pre class="language-swift"><code><span class="token comment">/// 扩展 String.StringInterpolation</span>
<span class="token keyword">extension</span> <span class="token builtin">String</span><span class="token punctuation">.</span><span class="token builtin">StringInterpolation</span> <span class="token punctuation">{</span>
    <span class="token comment">/// 实现 appendInterpolation</span>
    <span class="token comment">/// 此处入参为 Date 类型，只对 Date 类型有效</span>
    <span class="token keyword">mutating</span> <span class="token keyword">func</span> <span class="token function">appendInterpolation</span><span class="token punctuation">(</span><span class="token number">_</span> value<span class="token punctuation">:</span> <span class="token builtin">Date</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">let</span> formatter <span class="token operator">=</span> <span class="token function">DateFormatter</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
        formatter<span class="token punctuation">.</span>dateFormat <span class="token operator">=</span> <span class="token string">&quot;yyyy-MM-dd HH:mm&quot;</span>
        <span class="token function">appendLiteral</span><span class="token punctuation">(</span>formatter<span class="token punctuation">.</span><span class="token function">string</span><span class="token punctuation">(</span>from<span class="token punctuation">:</span> value<span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span>

    <span class="token comment">/// 可以带有多个参数</span>
    <span class="token keyword">mutating</span> <span class="token keyword">func</span> <span class="token function">appendInterpolation</span><span class="token punctuation">(</span><span class="token number">_</span> value<span class="token punctuation">:</span> <span class="token builtin">Date</span><span class="token punctuation">,</span> formatterStr<span class="token punctuation">:</span> <span class="token builtin">String</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">let</span> formatter <span class="token operator">=</span> <span class="token function">DateFormatter</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
        formatter<span class="token punctuation">.</span>dateFormat <span class="token operator">=</span> formatterStr
        <span class="token function">appendLiteral</span><span class="token punctuation">(</span>formatter<span class="token punctuation">.</span><span class="token function">string</span><span class="token punctuation">(</span>from<span class="token punctuation">:</span> value<span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

<span class="token function">print</span><span class="token punctuation">(</span><span class="token string">&quot;\(Date())&quot;</span><span class="token punctuation">)</span>
<span class="token function">print</span><span class="token punctuation">(</span><span class="token string">&quot;\(Date(), formatterStr:  &quot;</span><span class="token constant">HH</span><span class="token punctuation">:</span>mm<span class="token punctuation">:</span>ss<span class="token string">&quot;)&quot;</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br></div></div></section> <section aria-hidden="true" id="输出" role="tabpanel" class="tabs-component-panel" style="display:none;"><p>2020-03-18 15:20
15:20:18</p></section></div></div> <div class="custom-block tip"><p class="custom-block-title">提示</p> <p>通过在扩展中实现多个不同的  <code>appendInterpolation</code>  方法，我们就可以实现对不同数据进行格式化输出，方法中的  <code>appendLiteral</code>  将最终处理的结果添加到原始字符串上，如果遗漏则会变成插入空字符串</p></div> <h2 id="扩展自定义类型"><a href="#扩展自定义类型" class="header-anchor">#</a> 扩展自定义类型</h2> <p>实际上我们不止可以扩展原始的  <code>String</code> , 通过遵循  <code>ExpressibleByStringLiteral</code>  与  <code>ExpressibleByStringInterpolation</code>  协议可以让自定义的类型具备通过字符串初始化并插值的功能</p> <h3 id="创建自定义类型"><a href="#创建自定义类型" class="header-anchor">#</a> 创建自定义类型</h3> <p>首先我们创建一个用来进行扩展的类型，例如构建一个可以通过插值方式生成属性字符串的新类型  <code>AttributedString</code></p> <div class="language-swift line-numbers-mode"><pre class="language-swift"><code><span class="token comment">/// 创建一个用来测试的类型，里面仅有一个属性</span>
<span class="token keyword">struct</span> <span class="token builtin">AttributedString</span> <span class="token punctuation">{</span>
    <span class="token keyword">let</span> attributedString<span class="token punctuation">:</span> <span class="token builtin">NSAttributedString</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><p>现在  <code>AttributedString</code>  只是一个普通的结构体，接下来我们让它可以通过字符串初始化</p> <h3 id="遵循-expressiblebystringliteral-协议"><a href="#遵循-expressiblebystringliteral-协议" class="header-anchor">#</a> 遵循  <code>ExpressibleByStringLiteral</code>  协议</h3> <p>首先我们通过扩展方法遵循  <code>ExpressibleByStringLiteral</code>  协议并实现  <code>ExpressibleByStringLiteral</code>  协议中的初始化方法  <code>init(stringLiteral: String)</code> ，当我们自定义类在通过没有插值的字符串初始化时会执行这个方法来初始化</p> <div class="language-swift line-numbers-mode"><pre class="language-swift"><code><span class="token comment">/// 实现协议并实现其中的初始化方法</span>
<span class="token keyword">extension</span> <span class="token builtin">AttributedString</span><span class="token punctuation">:</span> <span class="token builtin">ExpressibleByStringLiteral</span> <span class="token punctuation">{</span>
    <span class="token comment">/// 没有插值的字符串会执行这个方法初始化</span>
    <span class="token keyword">init</span><span class="token punctuation">(</span>stringLiteral<span class="token punctuation">:</span> <span class="token builtin">String</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        attributedString <span class="token operator">=</span> <span class="token function">NSAttributedString</span><span class="token punctuation">(</span>string<span class="token punctuation">:</span> stringLiteral<span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><h3 id="遵循-expressiblebystringinterpolation-协议"><a href="#遵循-expressiblebystringinterpolation-协议" class="header-anchor">#</a> 遵循  <code>ExpressibleByStringInterpolation</code>  协议</h3> <p>遵循  <code>ExpressibleByStringInterpolation</code>  协议需要我们实现其初始化方法  <code>init(stringInterpolation: StringInterpolation)</code> ，当使用带有插值的字符串初始化时会执行这个方法来初始化。同时我们还要添加一个类型为  <code>StringInterpolation</code>  的子类型并让其遵循  <code>StringInterpolationProtocol</code>  协议，这个类型用来对插值进行处理，初始化方法的参数就是这个类型</p> <p>在  <code>StringInterpolation</code>  子类型中我们需要实现其初始化方法  <code>init(literalCapacity: Int, interpolationCount: Int)</code>  在这里可以进行初始化等操作，实现方法  <code>appendLiteral(_ literal:String)</code> , 这个方法用来处理初始化字符串中非插值的部分，同时实现一个或多个不同的  <code>appendInterpolation</code>  方法，这个方法就如同上面扩展 Stirng 一样用来对不同类型的插值进行处理</p> <div class="custom-block tip"><p>在利用带有插值的字符串初始化时，会首先调用  <code>StringInterpolation</code>  子类型中的初始化方法，然后按字符串顺序依次解析，根据是否是插值以及插值的类型来调用  <code>appendLiteral</code>  和  <code>appendInterpolation</code>  方法，最后调用  <code>init(stringInterpolation: StringInterpolation)</code>  构建完成</p></div> <div class="language-swift line-numbers-mode"><pre class="language-swift"><code><span class="token comment">/// 实现协议并实现其中的方法</span>
<span class="token keyword">extension</span> <span class="token builtin">AttributedString</span><span class="token punctuation">:</span> <span class="token builtin">ExpressibleByStringInterpolation</span> <span class="token punctuation">{</span>
    <span class="token comment">/// `StringInterpolation` 子类型，用来处理插值</span>
    <span class="token keyword">struct</span> <span class="token builtin">StringInterpolation</span><span class="token punctuation">:</span> <span class="token builtin">StringInterpolationProtocol</span> <span class="token punctuation">{</span>
    
        <span class="token comment">/// 这里创建可变属性字符串组成最后的结果</span>
        <span class="token keyword">let</span> attributedString<span class="token punctuation">:</span><span class="token builtin">NSMutableAttributedString</span>
        
        <span class="token comment">/// 实现初始化方法</span>
        <span class="token keyword">init</span><span class="token punctuation">(</span>literalCapacity<span class="token punctuation">:</span> <span class="token builtin">Int</span><span class="token punctuation">,</span> interpolationCount<span class="token punctuation">:</span> <span class="token builtin">Int</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            attributedString <span class="token operator">=</span> <span class="token function">NSMutableAttributedString</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
        <span class="token punctuation">}</span>
        
        <span class="token comment">/// 实现 `appendLiteral` 方法,当遇到非插值部分时会调用该方法进行组合</span>
        <span class="token keyword">func</span> <span class="token function">appendLiteral</span><span class="token punctuation">(</span><span class="token number">_</span> literal<span class="token punctuation">:</span><span class="token builtin">String</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token comment">/// 把不是插值部分的字符串拼接到结果上</span>
            <span class="token comment">/// 此处可以对非插值部分进行处理</span>
            attributedString<span class="token punctuation">.</span><span class="token function">append</span><span class="token punctuation">(</span><span class="token function">NSAttributedString</span><span class="token punctuation">(</span>string<span class="token punctuation">:</span> literal<span class="token punctuation">)</span><span class="token punctuation">)</span>
        <span class="token punctuation">}</span>
        
        <span class="token comment">/// 实现 `appendInterpolation` 方法,当遇到插值部分时会调用该方法进行处理</span>
        <span class="token comment">/// 可以实现多个来对不同类型的插值进行处理</span>
        <span class="token keyword">func</span> <span class="token function">appendInterpolation</span><span class="token punctuation">(</span><span class="token number">_</span> value<span class="token punctuation">:</span> <span class="token builtin">String</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token comment">/// 添加插值部分到结果上</span>
            attributedString<span class="token punctuation">.</span><span class="token function">append</span><span class="token punctuation">(</span><span class="token function">NSAttributedString</span><span class="token punctuation">(</span>string<span class="token punctuation">:</span> value<span class="token punctuation">)</span><span class="token punctuation">)</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
    
    <span class="token comment">/// 插值字符串会执行该初始化方法</span>
    <span class="token keyword">init</span><span class="token punctuation">(</span>stringInterpolation<span class="token punctuation">:</span> <span class="token builtin">StringInterpolation</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        attributedString <span class="token operator">=</span> <span class="token function">NSAttributedString</span><span class="token punctuation">(</span>attributedString<span class="token punctuation">:</span> stringInterpolation<span class="token punctuation">.</span>attributedString<span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br><span class="line-number">27</span><br><span class="line-number">28</span><br><span class="line-number">29</span><br><span class="line-number">30</span><br><span class="line-number">31</span><br><span class="line-number">32</span><br><span class="line-number">33</span><br></div></div><h3 id="使用"><a href="#使用" class="header-anchor">#</a> 使用</h3> <p>通过上面的几个步骤我们构建了一个简单的结构体类型  <code>AttributedString</code> , 这个类型可以通过插值字符串初始化并可以返回一个属性字符串</p> <div class="language-swift line-numbers-mode"><pre class="language-swift"><code><span class="token keyword">let</span> result<span class="token punctuation">:</span> <span class="token builtin">AttributedString</span> <span class="token operator">=</span> <span class="token string">&quot;测试<span class="token interpolation"><span class="token delimiter variable">\(</span><span class="token string">&quot;插入一个值&quot;</span><span class="token delimiter variable">)</span></span>&quot;</span>
<span class="token function">print</span><span class="token punctuation">(</span>result<span class="token punctuation">.</span>attributedString<span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p>通过添加更多的  <code>appendInterpolation</code>  方法可以处理更多不同类型的插值</p></div> <footer class="page-edit" style="display:none;"><!----> <!----></footer> <!----> <!----></main> <!----> <div class="comments-wrapper" data-v-0cb1c278><div class="valine-wrapper"><div id="valine"></div></div></div></div></div></div></div></div><div class="global-ui"><div class="back-to-ceiling" style="right:1rem;bottom:6rem;width:2.5rem;height:2.5rem;border-radius:.25rem;line-height:2.5rem;display:none;" data-v-a81d141e data-v-a81d141e><svg t="1574745035067" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5404" class="icon" data-v-a81d141e><path d="M526.60727968 10.90185116a27.675 27.675 0 0 0-29.21455937 0c-131.36607665 82.28402758-218.69155461 228.01873535-218.69155402 394.07834331a462.20625001 462.20625001 0 0 0 5.36959153 69.94390903c1.00431239 6.55289093-0.34802892 13.13561351-3.76865779 18.80351572-32.63518765 54.11355614-51.75690182 118.55860487-51.7569018 187.94566865a371.06718723 371.06718723 0 0 0 11.50484808 91.98906777c6.53300375 25.50556257 41.68394495 28.14064038 52.69160883 4.22606766 17.37162448-37.73630017 42.14135425-72.50938081 72.80769204-103.21549295 2.18761121 3.04276886 4.15646224 6.24463696 6.40373557 9.22774369a1871.4375 1871.4375 0 0 0 140.04691725 5.34970492 1866.36093723 1866.36093723 0 0 0 140.04691723-5.34970492c2.24727335-2.98310674 4.21612437-6.18497483 6.3937923-9.2178004 30.66633723 30.70611158 55.4360664 65.4791928 72.80769147 103.21549355 11.00766384 23.91457269 46.15860503 21.27949489 52.69160879-4.22606768a371.15156223 371.15156223 0 0 0 11.514792-91.99901164c0-69.36717486-19.13165746-133.82216804-51.75690182-187.92578088-3.42062944-5.66790279-4.76302748-12.26056868-3.76865837-18.80351632a462.20625001 462.20625001 0 0 0 5.36959269-69.943909c-0.00994388-166.08943902-87.32547796-311.81420293-218.6915546-394.09823051zM605.93803103 357.87693858a93.93749974 93.93749974 0 1 1-187.89594924 6.1e-7 93.93749974 93.93749974 0 0 1 187.89594924-6.1e-7z" p-id="5405" data-v-a81d141e></path><path d="M429.50777625 765.63860547C429.50777625 803.39355007 466.44236686 1000.39046097 512.00932183 1000.39046097c45.56695499 0 82.4922232-197.00623328 82.5015456-234.7518555 0-37.75494459-36.9345906-68.35043303-82.4922232-68.34111062-45.57627738-0.00932239-82.52019037 30.59548842-82.51086798 68.34111062z" p-id="5406" data-v-a81d141e></path></svg></div><canvas id="vuepress-canvas-ribbon"></canvas><div class="my-popup" style="display:none;" data-v-3414bdeb><div class="my-popup-container" data-v-3414bdeb><div class="my-popup-exit" data-v-3414bdeb></div> <img src="" alt data-v-3414bdeb></div></div><div data-v-2ebabc0c></div><div class="kanbanniang" data-v-3b0f9b07><div class="banniang-container" style="display:;" data-v-3b0f9b07><div class="messageBox" style="right:68px;bottom:230px;display:none;" data-v-3b0f9b07>
      欢迎来到 KnightSama‘s Blog
    </div> <div class="operation" style="right:90px;bottom:40px;display:;" data-v-3b0f9b07><i class="kbnfont kbn-ban-home ban-home" data-v-3b0f9b07></i> <i class="kbnfont kbn-ban-message message" data-v-3b0f9b07></i> <i class="kbnfont kbn-ban-close close" data-v-3b0f9b07></i> <a target="_blank" href="https://vuepress-theme-reco.recoluan.com/views/plugins/kanbanniang.html" data-v-3b0f9b07><i class="kbnfont kbn-ban-info info" data-v-3b0f9b07></i></a> <i class="kbnfont kbn-ban-theme skin" style="display:;" data-v-3b0f9b07></i></div> <canvas id="banniang" width="200" height="260" class="live2d" style="right:90px;bottom:-20px;opacity:0.9;" data-v-3b0f9b07></canvas></div> <div class="showBanNiang" style="display:none;" data-v-3b0f9b07>
    看板娘
  </div></div></div></div>
    <script src="/assets/js/app.a2483de7.js" defer></script><script src="/assets/js/4.0078dadf.js" defer></script><script src="/assets/js/1.c3e7d2b0.js" defer></script><script src="/assets/js/26.70698c07.js" defer></script>
  </body>
</html>
